package com.hy.controller.tools;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import com.google.code.kaptcha.Producer;
import com.hy.domain.dto.R;
import com.hy.util.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import static com.hy.util.RedisConstants.CODE_TTL;

@RestController
public class KaptchaController {
    @Autowired
    private Producer producer;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/codeImg")
    public R code(HttpServletResponse response, HttpSession session) {
//        R result = new R();
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);

        FastByteArrayOutputStream out = new FastByteArrayOutputStream();

        // 验证码唯一标识
        String uuid = UUID.randomUUID().toString(true);
        try {
            response.setContentType("image/png");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            ImageIO.write(image,"png", out);
            // 保存uuid
            session.setAttribute("uuid", uuid);
            String key = RedisConstants.LOGIN_CODE_KEY + uuid;
            stringRedisTemplate.opsForValue().set(key, code, CODE_TTL, TimeUnit.MINUTES);
        } catch (IOException e) {
            R.fail(e.getMessage());
        }

        HashMap<String, Object> map = new HashMap<>();

        map.put("uuid",uuid);
        map.put("img", Base64.encode(out.toByteArray()));

        return R.ok(map);
    }
}
